﻿using System;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using VOD.Models;
using VOD.ViewModels;

namespace VOD.Controllers
{
    public class VideoController : Controller
    {
        VODEntities db = new VODEntities();

        // 默认跳转至/Video/Movie 电影频道
        // GET: /Video/
        public ActionResult Index()
        {
            return RedirectToAction("Movie");
        }

        /// <summary>
        /// 频道跳转
        /// </summary>
        /// <param name="id">频道ID</param>
        /// <returns></returns>
        public ActionResult Channel(int id)
        {
            switch (id)
            {
                case 2:
                    return RedirectToAction("Index", "Movie");
                case 3:
                    return RedirectToAction("Index", "TV");
                case 4:
                    return RedirectToAction("Index", "Cartoon");
                case 5:
                    return RedirectToAction("Index", "Variety");
            }
            return RedirectToAction("Index", "Home");
        }

        //频道首页栏目列表
        public ActionResult Column(string colTitle, int? type, int categoryID, int? areaID, string url)
        {
            //筛选出此频道的所有电影
            var videos = db.Videos
                .Include(v => v.VideoLanguage)
                .Include(v => v.VideoAndTypes.Select(t => t.VideoType))
                .Include(t => t.PlayRecords)
                .Where(v => v.Recycled != 1 && v.CategoryID == categoryID)
                .OrderByDescending(v => v.UpdateDate)
                .ToList();
            if (type > 0)
            {
                //类别
                videos = videos.Where(v => v.VideoAndTypes.Any(t => t.TypeID == type)).ToList();
            }
            if (areaID > 0)
            {
                //类别
                videos = videos.Where(v => v.AreaID == areaID).ToList();
            }
            ViewBag.ColTitle = colTitle;
            videos = videos.Take(5).ToList();
            return View(videos);
        }

        // 获取排行榜信息
        // GET: /Video/TopRank
        public ActionResult TopRank()
        {
            var today = DateTime.Today;
            var todayOfWeek = Convert.ToInt32(today.DayOfWeek);
            var monday = today.AddDays(-todayOfWeek + 1);
            //var videos = db.v_VideoWeekRank.Take(10);
            var videos = db.Videos
                .Include(v => v.PlayRecords)
                .Include(v => v.VideoCategory)
                .Where(v => v.Recycled != 1)
                .ToList();
            foreach (var video in videos)
            {
                video.PlayRecords = video.PlayRecords.Where(p => p.PlayDate > monday).ToList();
            }
            videos = videos.OrderByDescending(v => v.PlayRecords.Count).Take(10).ToList();
            return View(videos);
        }

        // GET: /Video/DayRank/5
        /// <summary>
        /// 获取日排行榜
        /// </summary>
        /// <param name="categoryID">需要获取日排行榜的分类ID</param>
        /// <returns></returns>
        [OutputCache(Duration = 30)]
        public ActionResult MiniRank(int id = 1, string filter = "month")
        {
            var videos = db.Videos
                .Include(v => v.VideoCategory)
                .Include(v => v.PlayRecords)
                .Where(v => v.CategoryID == id && v.Recycled != 1)
                .ToList();
            filter = filter.ToLower();
            DateTime today = DateTime.Today;
            DateTime date = new DateTime();
            switch (filter)
            {
                case "day":
                    date = today.AddDays(-1);
                    break;
                case "week":
                    var todayOfWeek = Convert.ToInt32(today.DayOfWeek);
                    date = today.AddDays(-todayOfWeek + 1);
                    break;
                case "month":
                    var todayOfMonth = Convert.ToInt32(today.Day - 1);
                    date = today.AddDays(-todayOfMonth);
                    break;
            }
            foreach (var video in videos)
            {
                video.PlayRecords = video.PlayRecords.Where(p => p.PlayDate >= date).ToList();
            }
            videos = videos
                .OrderByDescending(v => v.PlayRecords.Count)
                .Take(10).ToList();
            return View(videos);
        }

        /// <summary>
        /// 频道排行
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult ChannelRank(int id, int amout = 10)
        {
            var videos = db.Videos
                .Include(v => v.PlayRecords)
                .Where(v => v.Recycled != 1 && v.CategoryID == id)
                .OrderByDescending(v => v.PlayRecords.Count)
                .Take(amout).ToList();
            return View(videos);
        }

        /// <summary>
        /// 首页栏目显示（电影、电视、动漫）
        /// </summary>
        /// <param name="id">CategoryID</param>
        /// <returns></returns>
        public ActionResult HomeColumn(int id)
        {
            var now = DateTime.Now.Date.AddDays(-1);
            var videos = db.Videos
                .Include(v => v.VideoAndTypes.Select(t => t.VideoType))
                .Include(v => v.VideoCategory)
                .Where(v => v.CategoryID == id && v.Recycled != 1)
                .OrderByDescending(v => v.UpdateDate)
                .Take(11);
            var categoryName = db.VideoCategories.Single(c => c.CategoryID == id).CategoryName;
            ViewBag.UpdateNum = db.Videos.Count(v => v.UpdateDate >= now && v.CategoryID == id);
            ViewBag.CategoryID = id;
            switch (categoryName)
            {
                case "电影":
                    ViewBag.CategoryEName = "movie";
                    break;
                case "电视":
                    ViewBag.CategoryEName = "tv";
                    break;
                case "动漫":
                    ViewBag.CategoryEName = "cartoon";
                    break;
                case "综艺":
                    ViewBag.CategoryEName = "vatiety";
                    break;
            }
            ViewBag.CategoryName = categoryName;
            return View(videos);
        }

        // 首页综艺栏目
        // GET: Video/HomeVarietyColumn
        public ActionResult HomeVarietyColumn()
        {
            var now = DateTime.Now.Date.AddDays(-1);
            var videos = db.Videos
                .Where(v => v.CategoryID == 5 && v.Recycled != 1)
                .OrderByDescending(v => v.UpdateDate).Take(6);
            ViewBag.UpdateNum = db.Videos.Count(v => v.UpdateDate >= now && v.CategoryID == 5 && v.Recycled != 1);
            return View(videos);
        }

        //播放界面
        public ActionResult Play(int id, int orderNum = 1)
        {
            var video = db.Videos
                .Include(v => v.VideoArea)
                .Include(v => v.VideoLanguage)
                .Include(v => v.VideoAndTypes.Select(t => t.VideoType)).Single(v => v.VideoID == id);
            ViewBag.OrderNum = orderNum;
            return View(video);
        }

        //调用播放器
        public ActionResult Player(int id, int orderNum = 1)
        {
            Player play = new Player() { VideoID = id, OrderNum = orderNum };
            play.VideoName = db.Videos.Find(id).Name;
            var url = db.VideoUrls
                .OrderBy(f => f.VideoOrder)
                .Where(f => f.VideoID == id && f.VideoOrder >= orderNum)
                .Take(1).ToList();
            if (url.Count >= 1)
            {
                //获取需要播放的url
                play.Url = url[0].VideoURL;
                var playRecord = new PlayRecord
                {
                    VideoPartID = url[0].VideoPartID,
                    VideoID = id,
                };
                PlayRecorder(playRecord);
            }
            play.OrderNum = orderNum;
            //用于生成下条url的播放地址
            //play.NextUrl = Url.Action("Player", "Video", new { id = id, orderNum = orderNum + 1 });
            ViewBag.Player = db.Sysconfigs.FirstOrDefault().Player;
            return View(play);
        }

        //新增点播记录
        private void PlayRecorder(PlayRecord playRecord)
        {
            playRecord.PlayDate = DateTime.Now;
            if (HttpContext.Request.IsAuthenticated)
            {
                playRecord.UserID = new Guid(Membership.GetUser().ProviderUserKey.ToString());
            }
            db.PlayRecords.Add(playRecord);
            db.SaveChanges();
        }

        public ActionResult ShowRecord()
        {
            var records = db.PlayRecords
                        .Include(r => r.Video)
                        .Include(r => r.VideoUrl)
                        .OrderByDescending(r => r.PlayDate)
                        .ToList();
            if (Request.IsAuthenticated)
            {
                var userID = new Guid(Membership.GetUser().ProviderUserKey.ToString());
                records = records.Where(r => r.UserID == userID).ToList();
            }
            return View(records);
        }

        public ActionResult PlayList(int id)
        {
            var playList = db.VideoUrls.Where(u => u.VideoID == id).OrderBy(u => u.VideoOrder).ToList();
            return View(playList);
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}
